import { AcGameObject } from "./AcGameObject";
import { Wall } from "./Wall";
import { Snake } from "./Snake";
// import { event } from "jquery";
export class GameMap extends AcGameObject {
  constructor(ctx, parent, store){
    super();

    this.ctx = ctx;
    this.parent = parent;
    this.store = store;
    this.L = 0;

    this.rows = 13;
    this.cols = 14;

    this.inner_walls_count = 20;
    this.walls = [];
    this.snakes = [
      new Snake({ id: 0, color: "#4876ea", r: this.rows - 2, c: 1 }, this),
      new Snake({ id: 1, color: "#f64445", r: 1, c: this.cols - 2 }, this),
    ];

  }

  // check_connectivity(g, sx, sy, tx, ty) { //判断连通性
  //   if(sx == tx && sy == ty) return true;
  //   g[sx][sy] = true;
  //   let dx = [-1, 0, 1, 0], dy = [0, 1, 0, -1];
  //   for (let i = 0; i < 4; i ++ ) {
  //     let nx = sx + dx[i], ny = sy + dy[i];
  //     if (!g[nx][ny] && this.check_connectivity(g, nx, ny, tx, ty)) return true;
  //   }
  //   return false;
  // }

  create_walls() {
    const g = this.store.state.pk.gamemap;
    // const g = [];
    // for(let r = 0; r < this.rows; r ++ ){
    //   g[r] = [];
    //   for(let c = 0; c < this.cols; c ++ ){
    //     g[r][c] = false;
    //   }
    // }

    // // 给四周加上障碍物
    // for(let r = 0; r < this.rows; r ++ ) {
    //   g[r][0] = g[r][this.cols - 1] = true;
    // }
    // for(let c = 0; c < this.cols; c ++ ) {
    //   g[0][c] = g[this.rows - 1][c] = true;
    // }
    // // 图上随机生成障碍物
    // for(let i = 0; i < this.inner_walls_count / 2; i ++ ) {
    //   for(let j = 0; j < 1000; j ++ ) {
    //     let r = parseInt(Math.random() * this.rows);
    //     let c = parseInt(Math.random() * this.cols);
    //     if(g[r][c] || g[this.rows - 1 - r][this.cols - 1 - c]) continue;
    //     if(r == this.rows - 2 && c == 1) continue;
    //     g[r][c] = g[this.rows - 1 - r][this.cols - 1 - c] = true;
    //     break;
    //   }
    // }

    // const copy_g = JSON.parse(JSON.stringify(g))//复制一个bool数组
    // if(!this.check_connectivity(copy_g, this.rows - 2, 1, 1, this.cols - 2)) return false;
    // 上色
    for(let r = 0; r < this.rows; r ++) {
      for(let c = 0; c < this.cols; c ++) {
        if(g[r][c]) {
          this.walls.push(new Wall(r, c, this));
        }
      }
    }

    // return true;
  }

  add_listening_events() {
    this.ctx.canvas.focus();
    
    // const [snake0, snake1] = this.snakes;
    this.ctx.canvas.addEventListener("keydown", e => {
      // if (e.key === 'w') snake0.set_direction(0);
      // else if (e.key === 'd') snake0.set_direction(1);
      // else if (e.key === 's') snake0.set_direction(2);
      // else if (e.key === 'a') snake0.set_direction(3);
      // else if (e.key === 'ArrowUp') snake1.set_direction(0);
      // else if (e.key === 'ArrowRight') snake1.set_direction(1);
      // else if (e.key === 'ArrowDown') snake1.set_direction(2);
      // else if (e.key === 'ArrowLeft') snake1.set_direction(3);
      let d = -1;
      if (e.key === 'w') d = 0;
      else if (e.key === 'd') d = 1;
      else if (e.key === 's') d = 2;
      else if (e.key === 'a') d = 3;

      if (d >= 0) {
        this.store.state.pk.socket.send(JSON.stringify({
          event: "move",
          direction: d,
        }));
      }
    });
  }

  start() { 
    // for(let i = 0;i < 1000; i ++ ) {
    //   if(this.create_walls()) break;
    // }
    this.create_walls();
    this.add_listening_events();
  }

  update_size() { //辅助函数，更新变长
    this.L = parseInt(Math.min(this.parent.clientWidth / this.cols, this.parent.clientHeight / this.rows));
    this.ctx.canvas.width = this.L * this.cols;
    this.ctx.canvas.height = this.L * this.rows;
  }

  check_ready() { //判断两条蛇是否都准备好下一回合了
    for (const snake of this.snakes) {
      if (snake.status !== "idle") return false;
      if (snake.direction === -1) return false;
    }
    return true;
  }

  next_step() { //让两条蛇进入下一回合
    for(const snake of this.snakes) {
      snake.next_step();
    }
  }

  check_valid(cell) { //检测目标位置是否合法（没有撞到两条蛇的身体和障碍物）
    for (const wall of this.walls) { //of枚举值，in枚举下标
      if (wall.r === cell.r && wall.c === cell.c) return false;
    }
    for(const snake of this.snakes) {
      let k = snake.cells.length;
      if (!snake.check_tail_increasing()) { //特判：🐍头追🐍尾,当蛇尾会前进的时候，设为不用判断
        k --;
      }
      for(let i = 0; i < k; i ++ ){
        if(snake.cells[i].r === cell.r && snake.cells[i].c === cell.c) return false;
      }
    }
    return true;
  }

  update() {
    this.update_size();
    if (this.check_ready()) {
      this.next_step();
    }
    this.render();
  }

  render() {
    // 渲染格子
    const color_even = "#aad751", color_odd = "#a2d048";
    for(let r = 0; r < this.rows; r ++ ){
      for(let c = 0; c < this.cols; c ++ ){
        if((r + c) & 1) this.ctx.fillStyle = color_odd;
        else this.ctx.fillStyle = color_even;
        this.ctx.fillRect(c * this.L, r * this.L, this.L, this.L);
      }
    }
  }

}